package cn.yuanqiao.web.controller.archive.archiveBorrow;

import java.io.*;
import java.net.URL;
import java.text.ParseException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.activiti.domain.ActivitiPackage;
import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaDocumentMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCategoryService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.archiveBorrow.domain.YqdaBorrowItemPage;
import cn.yuanqiao.archive.archiveBorrow.domain.YqdaborrowItem;
import cn.yuanqiao.archive.archiveBorrow.service.IYqdaBorrowItemPageService;
import cn.yuanqiao.archive.report.service.reportService;
import cn.yuanqiao.archive.utils.FilePageCounter;
import cn.yuanqiao.archive.wenjianzhengli.domain.Yqdatransdoc;
import cn.yuanqiao.common.constant.SecurityConstants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.*;
import cn.yuanqiao.feignService.RemoteSysDeptService;
import cn.yuanqiao.system.service.ISysDeptService;
import cn.yuanqiao.system.service.ISysUserService;
import cn.yuanqiao.common.core.context.ResponseUtils;
import com.alibaba.fastjson2.JSONObject;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.archiveBorrow.domain.YqDaBorrow;
import cn.yuanqiao.archive.archiveBorrow.service.IYqDaBorrowService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * archiveBorrowController
 *
 * @author yuanqiao
 * @date 2023-07-14
 */
@RestController
@RequestMapping("/archive/archiveBorrow")
public class YqDaBorrowController extends BaseController {
    @Autowired
    private IYqDaBorrowService yqDaBorrowService;

    @Autowired
    private RemoteActivitiService remoteActivitiService;

    @Autowired
    private RemoteSysDeptService remoteSysDeptService;

    @Autowired
    private IYqdaBorrowItemPageService yqdaBorrowItemPageService;

    @Autowired
    private ITenantCategoryService tenantCategoryService;

    @Autowired
    private ISysUserService remoteUserService;

    @Autowired
    @Qualifier("ExcelFilePageCounter")
    FilePageCounter ExcelFilePageCounter;

    @Autowired
    @Qualifier("OfdFilePageCounter")
    FilePageCounter OfdFilePageCounter;

    @Autowired
    @Qualifier("PdfFilePageCounter")
    FilePageCounter PdfFilePageCounter;

    @Autowired
    @Qualifier("WordFilePageCounter")
    FilePageCounter WordFilePageCounter;

    @Autowired
    private ITenantSysDictTypeService dictTypeService;

    @Autowired
    private reportService reportService;

    @Autowired
    private TenantYqdaDocumentMapper documentMapper;

    @Autowired
    private TenantCategoryMapper categoryMapper;

    @Autowired
    private ITenantSysConfigService sysConfigService;

    /**
     * 查询archiveBorrow列表
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:list')")
    @GetMapping("/list")
    public TableDataInfo list(YqDaBorrow yqDaBorrow) throws ParseException {
        updateAllStatus(SecurityUtils.getUserId());
        startPage();
        yqDaBorrow.setTenantCode(SecurityUtils.getTenantCode());
        if (!SecurityUtils.isDagly()){
            yqDaBorrow.setBorrowUser(SecurityUtils.getUserId());
        }
        if (yqDaBorrow.getParams().get("beginCreateTime") != null && yqDaBorrow.getParams().get("endCreateTime") != null) {
            String begin = String.valueOf(yqDaBorrow.getParams().get("beginCreateTime")).replaceAll(" .*", "") + "  00:00:00.000";
            String end = String.valueOf(yqDaBorrow.getParams().get("endCreateTime")).replaceAll(" .*", "") + " 23.59.59.000";
            yqDaBorrow.setBeginCreateTime(begin);
            yqDaBorrow.setEndCreateTime(end);
        }
        List<YqDaBorrow> list = yqDaBorrowService.selectYqDaBorrowList(yqDaBorrow);
        /*list.forEach(item->{
            if (item.getEndTime() != null&&!item.getStatus().equals(2)){
                Instant endTime = item.getEndTime().toInstant();
                LocalDateTime localEndTime = LocalDateTime.ofInstant(endTime, ZoneId.systemDefault());
                LocalDateTime localNowTime = LocalDateTime.now();
                if (localEndTime.isBefore(localNowTime)){
                    item.setStatus(3);
                }
            }

        });*/
        return getDataTable(list);
    }

    /**
     * 导出archiveBorrow列表
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:export')")
    @Log(title = "archiveBorrow", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqDaBorrow yqDaBorrow) {
        List<YqDaBorrow> list = yqDaBorrowService.selectYqDaBorrowList(yqDaBorrow);
        ExcelUtil<YqDaBorrow> util = new ExcelUtil<YqDaBorrow>(YqDaBorrow.class);
        util.exportExcel(response, list, "archiveBorrow数据");
    }

    /**
     * 获取archiveBorrow详细信息
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:query')")
    @GetMapping(value = "/{borrowId}")
    public AjaxResult getInfo(@PathVariable("borrowId") Long borrowId) {
        YqDaBorrow yqDaBorrow = yqDaBorrowService.selectYqDaBorrowByBorrowId(borrowId);
        /*if (yqDaBorrow.getEndTime() != null){
            Instant endTime = yqDaBorrow.getEndTime().toInstant();
            LocalDateTime localEndTime = LocalDateTime.ofInstant(endTime, ZoneId.systemDefault());
            LocalDateTime localNowTime = LocalDateTime.now();
            if (localEndTime.isBefore(localNowTime)){
                yqDaBorrow.setStatus(3);
                yqDaBorrow.getYqdaborrowItemList().forEach(item->item.setStatus("2".equalsIgnoreCase(item.getStatus())?"2":"3"));
            }
        }*/
        return success(yqDaBorrow);
    }

    /**
     * 新增archiveBorrow
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:add')")
    @Log(title = "archiveBorrow", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YqDaBorrow yqDaBorrow) {
        return toAjax(yqDaBorrowService.insertYqDaBorrow(yqDaBorrow));
    }

    /**
     * 修改archiveBorrow
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:edit')")
    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqDaBorrow yqDaBorrow) {
        return toAjax(yqDaBorrowService.updateYqDaBorrow(yqDaBorrow));
    }

    /**
     * 满意度评价
     *
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:pj')")
    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PutMapping("/editCast")
    public AjaxResult editCast(@RequestBody YqDaBorrow yqDaBorrow) {
        return toAjax(yqDaBorrowService.updateYqDaBorrowMyd(yqDaBorrow));
    }

    /**
     * 修改archiveBorrow
     */
    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAllStatus/{userId}")
    public R<Integer> updateAllStatus(@PathVariable("userId") Long userId) {
        return R.ok(yqDaBorrowService.updateAllStatus(userId));
    }



    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:edit')")
    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PutMapping("/reSubmitArchiveBorrow")
    public AjaxResult reSubmitArchiveBorrow(@RequestBody YqDaBorrow yqDaBorrow) {
        //yqDaBorrowService.updateYqDaBorrow(yqDaBorrow)
        YqDaBorrow select = yqDaBorrowService.selectYqDaBorrowByBorrowId(yqDaBorrow.getBorrowId());
        select.setYongtu(yqDaBorrow.getYongtu());
        select.setBorrowDays(yqDaBorrow.getBorrowDays());
        select.setStatus(4);
        select.setStartTime(null);
        select.setEndTime(null);
        select.setCreateTime(new Date(System.currentTimeMillis()));
        List<YqdaborrowItem> yqdaborrowItemList = select.getYqdaborrowItemList();
        List<Map<String, Object>> archiveData = new ArrayList<>();
        for (YqdaborrowItem yqdaborrowItem : yqdaborrowItemList) {
            String archiveId = yqdaborrowItem.getDaId();
            Long categoryId = yqdaborrowItem.getCategoryId();
            List<Map<String, Object>> archiveListByArchiveCategory = yqDaBorrowService.getArchiveListByArchiveCategory(categoryId, archiveId);
            archiveData.addAll(archiveListByArchiveCategory);
            yqdaborrowItem.setStatus("4");
        }
        Map<String, Object> variables = new HashMap<>();
        variables.put("archiveData", archiveData);
        variables.put("processVariables", select.toProcessMap());
        variables.put("archive_has_mj", "1");
        variables.put("archive_is_dept", "1");
        variables.put("archive_site_view", "1");
        variables.put("archive_type", "lt");
        R<ActivitiPackage> activitiPackageR = remoteActivitiService.startProcessWsArchiveBorrow(variables);
        select.setProcessId(activitiPackageR.getData().getProcessInstance().getId());
        return toAjax(yqDaBorrowService.updateYqDaBorrowStatus(select));
    }

    /**
     * 修改archiveBorrow
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:edit')")
    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PutMapping("/handleCancelProcess")
    public AjaxResult cancelBorrow(@RequestBody String borrowId) {
        YqDaBorrow yqDaBorrow = new YqDaBorrow();
        yqDaBorrow.setStatus(4);
        yqDaBorrow.setBorrowId(Long.valueOf(borrowId));
        return toAjax(yqDaBorrowService.endWorkFlowByInstanceId(yqDaBorrow));
    }

    /**
     * 删除archiveBorrow
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:remove')")
    @Log(title = "archiveBorrow", businessType = BusinessType.DELETE)
    @DeleteMapping("/{borrowIds}")
    public AjaxResult remove(@PathVariable Long[] borrowIds) {
        return toAjax(yqDaBorrowService.deleteYqDaBorrowByBorrowIds(borrowIds));
    }

    /**
     * 删除archiveBorrow
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:list')")
    @Log(title = "借阅管理", businessType = BusinessType.SELECT)
    @GetMapping("/getItem")
    public TableDataInfo getItem(YqdaborrowItem yqdaborrowItem) {
        yqdaborrowItem.setBorrowUserId(String.valueOf(SecurityUtils.getUserId()));
        startPage();
        return getDataTable(yqDaBorrowService.selectYqDaBorrowItemList(yqdaborrowItem));
    }

    /**
     * 修改archiveBorrow
     */
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:edit')")
    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PutMapping(value = {"/updateArchiveBorrowDate/{borrowId}/{borrowDays}/{status}", "/updateArchiveBorrowDate/{borrowId}/{borrowDays}/"})
    public R<Integer> updateArchiveBorrowDate(@PathVariable("borrowId") Long borrowId, @PathVariable("borrowDays") Long borrowDays, @PathVariable(value = "status", required = false) Integer status) {
        YqDaBorrow yqDaBorrow = new YqDaBorrow();
        yqDaBorrow.setBorrowId(borrowId);
        if (borrowDays != null) {
            yqDaBorrow.setStartTime(DateUtils.getNowDate());
            yqDaBorrow.setEndTime(DateUtils.addDate(DateUtils.getNowDate(), borrowDays));
        }
        if (status != null) {
            yqDaBorrow.setStatus(status);
        }
        return R.ok(yqDaBorrowService.updateArchiveBorrowDate(yqDaBorrow));
    }

    /**
     * downloadWaxPaperDocx
     *//*
    @Log(title = "archiveBorrow", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/downloadWaxPaperDocx")
    public ResponseEntity<byte[]> downloadWaxPaperDocx(@RequestBody YqDaBorrow yqDaBorrow)throws IOException {

        //return toAjax(yqdaborrowCarService.deleteYqdaborrowCarByArchiveIds(carIds));
        // 从resources目录下获取文件
        ClassPathResource classPathResource = new ClassPathResource("borrowModel/waxPaperCallForm.docx");

        // 读取文件流
        File file = classPathResource.getFile();
        FileInputStream fis = new FileInputStream(file);
        XWPFDocument document = new XWPFDocument(fis);
        AjaxResult info = getInfo(yqDaBorrow.getBorrowId());
        Map<String,String> keyMap = new HashMap<>();
        keyMap.put("{{DTMC}}","");
        keyMap.put("{{deptName}}",remoteSysDeptService.getInfoApi(yqDaBorrow.getBorrowDept()).getData().getDeptName());
        keyMap.put("{{userName}}","用户名");
        keyMap.put("{{userPhone}}",yqDaBorrow.getPhoneNum());
        keyMap.put("{{XMMC}}","项目名称");
        keyMap.put("{{LYMD}}","学习");
        keyMap.put("{{leaderName}}","leader");
        keyMap.put("{{borrowTime}}","20220102");

        for (XWPFTable table : document.getTables()) {
            // 遍历表格的行和单元格
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
                    // 在表格中查找关键字并替换
                    XWPFTableCell cell = table.getRow(i).getCell(j);
                    String cellText = cell.getText();
                    for (Map.Entry<String,String> item:keyMap.entrySet()){
                        String value = item.getValue()==null?"":item.getValue();
                        if (cellText.contains(item.getKey())) {
                            if (cellText.equals(item.getKey())){
                                int size = cell.getParagraphs().size();
                                for (int k = 0; k < size; k++) {
                                    cell.removeParagraph(0);
                                }
                                cellText = cellText.replace(item.getKey(), value);
                                // 添加新的段落和文本
                                XWPFParagraph newParagraph = cell.addParagraph();
                                XWPFRun run = newParagraph.createRun();
                                run.setText(cellText);
                                run.addCarriageReturn();
                                // 设置新的文本格式（如果需要的话）
                                run.setFontSize(14);
                            }else {
                                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                                Iterator<XWPFParagraph> iterator = paragraphs.iterator();
                                while (iterator.hasNext()){
                                    XWPFParagraph next = iterator.next();
                                    Iterator<XWPFRun> iteratorRun = next.getRuns().iterator();
                                    while (iteratorRun.hasNext()){
                                        XWPFRun run = iteratorRun.next();
                                        if (run.getText(0).equals(item.getKey())){
                                            System.out.println(run.getText(0));
                                            run.setText("", 0);
                                            run.setText(value);

                                        }
                                    }
                                }
                            }

                        }
                    }


                }
            }
        }
        FileOutputStream fos = new FileOutputStream(new File("d:/mnt/path/save/modifiedDoc.docx"));
        document.write(fos);
        // 从已保存的文件中创建 FileInputStream
        FileInputStream fileInputStream = new FileInputStream(new File("d:/mnt/path/save/modifiedDoc.docx"));

        // 将 FileInputStream 包装成 InputStream
        InputStream inputStream = (InputStream) fileInputStream;


        //InputStream inputStream = classPathResource.getInputStream();
        byte[] fileData = new byte[inputStream.available()];
        inputStream.read(fileData);

        // 设置响应头，指定文件名
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "蜡纸底图调用单.docx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 创建 ResponseEntity 并返回文件流
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(fileData, headers, HttpStatus.OK);
        return responseEntity;
    }*/

    /**
     * downloadWaxPaperDocx
     */
    @Log(title = "archiveBorrow", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/downloadWaxPaperDocx")
    public AjaxResult downloadWaxPaperDocx(@RequestBody YqDaBorrow yqDaBorrow) {
        AjaxResult info = getInfo(yqDaBorrow.getBorrowId());
        YqDaBorrow newBorrow = (YqDaBorrow) info.get("data");
        Date startTime = newBorrow.getStartTime();
        String borrowDate = "    年  月  日";
        if (startTime != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            borrowDate = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日";
        }
        String deptName = remoteSysDeptService.getInfoApi(newBorrow.getBorrowDept()).getData().getDeptName();
        String username = remoteUserService.selectUserById(newBorrow.getBorrowUser()).getNickName();
        String lymd = dictTypeService.selectDictDataByType("LYMD").stream()
                .filter(item -> item.getDictValue().equals(yqDaBorrow.getYongtu())).findFirst().get().getDictLabel();
        List<YqdaborrowItem> yqdaborrowItemList = newBorrow.getYqdaborrowItemList();
        StringBuilder archiveNames = new StringBuilder();
        StringBuilder archiveCodes = new StringBuilder();
        for (YqdaborrowItem item : yqdaborrowItemList) {
            Map<String, Object> archiveData = item.getArchiveData();
            String state = item.getFeedBack();
            TenantCategory tenantCategory = tenantCategoryService.selectTenanCategoryByID(item.getCategoryId());
            Integer type = tenantCategory.getType();
            System.out.println(111);
            if ("f".equals(state) && 3 == type) {
                String sql = "SELECT XMMC FROM " + tenantCategory.getItemTableName() + " WHERE ID = " +
                        "(SELECT ITEM_ID FROM " + SecurityUtils.getTenantCode().toUpperCase() + "_ITEM_FOLDER WHERE " +
                        "FOLDER_ID IN (SELECT FOLDER_ID FROM " + SecurityUtils.getTenantCode().toUpperCase() + "_YQDA_FOLDER " +
                        " WHERE DA_ID = " + item.getDaId() + "))";
                List<Map<String, Object>> list = yqDaBorrowService.executeSqlFunction(sql);
                //件层，直接拿图号
                if (list.size() != 0) {
                    list.forEach(xmmc -> archiveNames.append(xmmc.get("XMMC")));
                }
                if (item.getArchiveData().get("TH") != null) {
                    archiveCodes.append(item.getArchiveData().get("TH")).append(";");
                }
            } else if ("v".equals(state) && 3 == type) {
                String sql = "SELECT XMMC FROM " + tenantCategory.getItemTableName() + " WHERE ID = " +
                        "(SELECT ITEM_ID FROM " + SecurityUtils.getTenantCode().toUpperCase() + "_ITEM_FOLDER WHERE " +
                        "FOLDER_ID IN ( " + item.getDaId() + "))";
                List<Map<String, Object>> list = yqDaBorrowService.executeSqlFunction(sql);
                if (list.size() != 0) {
                    list.forEach(xmmc -> archiveNames.append(xmmc.get("XMMC")).append(";"));
                }

                String sqlTh = "SELECT TH FROM " + tenantCategory.getFileTableName() + " WHERE ID IN(SELECT DA_ID " +
                        "FROM " + SecurityUtils.getTenantCode().toUpperCase() + "_YQDA_FOLDER " +
                        " WHERE FOLDER_ID = " + item.getDaId() + ")";
                List<Map<String, Object>> listTh = yqDaBorrowService.executeSqlFunction(sqlTh);
                if (listTh.size() != 0) {
                    listTh.forEach(xmmc -> archiveNames.append(xmmc.get("TH")).append(";"));
                }
            } else if ("x".equals(state)) {
                if (item.getArchiveData().get("XMMC") != null) {
                    archiveCodes.append(item.getArchiveData().get("XMMC")).append(";");
                }

                String sqlTh = "SELECT TH FROM " + tenantCategory.getFileTableName() + " WHERE ID IN(SELECT DA_ID " +
                        "FROM " + SecurityUtils.getTenantCode().toUpperCase() + "_YQDA_FOLDER " +
                        " WHERE FOLDER_ID IN(SELECT FOLDER_ID FROM " + SecurityUtils.getTenantCode().toUpperCase() + "_ITEM_FOLDER" +
                        " WHERE ITEM_ID = " + item.getDaId() + "))";
                List<Map<String, Object>> listTh = yqDaBorrowService.executeSqlFunction(sqlTh);
                if (listTh.size() != 0) {
                    listTh.forEach(xmmc -> archiveNames.append(xmmc.get("TH")).append(";"));
                }
            }
            /*if (item.getArchiveData().get("TITLE")!=null){
                archiveNames.append(item.getArchiveData().get("TITLE")).append(";");
            }
            if (item.getArchiveData().get("XMMC")!=null){
                archiveNames.append(item.getArchiveData().get("XMMC")).append(";");
            }
            if (item.getArchiveData().get("DH")!=null){
                archiveCodes.append(item.getArchiveData().get("DH")).append(";");
            }*/
        }
        List<Map<String, Object>> data = remoteActivitiService.getProcessDateByProcessId(newBorrow.getProcessId()).getData();
        String borrowUseLeader = "";
        String planningOperationLeader = "";
        String archivesLeader = "";
        String borrowUseLeaderAgreeDate = "    年  月  日";
        String planningOperationLeaderAgreeDate = "    年  月  日";
        String archivesLeaderAgreeDate = "    年  月  日";
        for (Map<String, Object> item : data) {
            if (item.get("isAgree") == null || !String.valueOf(((LinkedHashMap) item.get("isAgree")).get("controlValue")).equals("同意")) {
                continue;
            }
            String assignee = remoteUserService.getUserInfo
                            (String.valueOf(item.get("assignee")), SecurityUtils.getTenantCode(), SecurityConstants.INNER)
                    .getData().getSysUser().getNickName();
            Date endTime = new Date(Long.valueOf(item.get("endTime").toString()));
            String approveTime = "    年  月  日";
            if (endTime != null) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endTime);
                approveTime = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日";
            }
            String activityName = String.valueOf(item.get("activityName"));
            if ("借阅人领导审批".equals(activityName)) {
                borrowUseLeader = assignee;
                borrowUseLeaderAgreeDate = approveTime;
            } else if ("计划经营处审批".equals(activityName)) {
                planningOperationLeader = assignee;
                planningOperationLeaderAgreeDate = approveTime;
            } else if ("档案馆领导审批".equals(activityName)) {
                archivesLeader = assignee;
                archivesLeaderAgreeDate = approveTime;
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("menuId", 2);
        jsonObject.put("categoryId", 123456);
        jsonObject.put("type", "dt");
        StringBuilder dataBuilder = new StringBuilder();
        dataBuilder.append("{\"data\":[");
        dataBuilder.append("{\"borrowDate\":\"").append(borrowDate).append("\",");              //借阅日期
        dataBuilder.append("\"borrowDept\":\"").append(deptName).append("\",");                  //借阅部门
        dataBuilder.append("\"borrowUserName\":\"").append(username).append("\",");           //借阅人姓名
        dataBuilder.append("\"borrowUserPhone\":\"").append(newBorrow.getPhoneNum()).append("\",");       //借阅人电话
        dataBuilder.append("\"borrowArchiveName\":\"").append(archiveNames.toString()).append("\","); //借阅档案名称
        dataBuilder.append("\"borrowArchiveCode\":\"").append(archiveCodes.toString()).append("\",");  //借阅档案档号
        dataBuilder.append("\"borrowUseTo\":\"").append(lymd).append("\",");                   //借阅用途
        dataBuilder.append("\"borrowUseLeader\":\"").append(borrowUseLeader).append("\",");                   //借阅用途
        dataBuilder.append("\"borrowUseLeaderAgreeDate\":\"").append(borrowUseLeaderAgreeDate).append("\",");                   //借阅用途
        dataBuilder.append("\"PlanningOperationLeader\":\"").append(planningOperationLeader).append("\",");                   //借阅用途
        dataBuilder.append("\"PlanningOperationLeaderAgreeDate\":\"").append(planningOperationLeaderAgreeDate).append("\",");                   //借阅用途
        dataBuilder.append("\"ArchivesLeader\":\"").append(archivesLeader).append("\",");                   //借阅用途
        dataBuilder.append("\"ArchivesLeaderAgreeDate\":\"").append(archivesLeaderAgreeDate).append("\"}");                   //借阅用途
        //dataBuilder.append("\"borrowApproveLeader\":\"").append(assignees).append("\"}");     //领导签字
        //dataBuilder.deleteCharAt(dataBuilder.length()-1);
        dataBuilder.append("]}");
        jsonObject.put("data", dataBuilder.toString());
        Map geturl = reportService.geturl(jsonObject);
        return success(geturl);
    }

    /**
     * downloadWaxPaperDocx
     */
    @Log(title = "archiveBorrow", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/downloadArchiveBorrowTable")
    public AjaxResult downloadArchiveBorrowTable(@RequestBody YqDaBorrow yqDaBorrow) throws IOException {
        AjaxResult info = getInfo(yqDaBorrow.getBorrowId());
        YqDaBorrow getInfo = (YqDaBorrow) info.get("data");
        Date startTime = getInfo.getStartTime();
        String borrowDate = "    年  月  日";
        if (startTime != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            borrowDate = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日";
        }
        String deptName = remoteSysDeptService.getInfoApi(getInfo.getBorrowDept()).getData().getDeptName();
        String username = remoteUserService.selectUserById(getInfo.getBorrowUser()).getNickName();
        String lymd = dictTypeService.selectDictDataByType("LYMD").stream()
                .filter(item -> item.getDictValue().equals(yqDaBorrow.getYongtu())).findFirst().get().getDictLabel();
        List<YqdaborrowItem> yqdaborrowItemList = getInfo.getYqdaborrowItemList();
        StringBuilder archiveNames = new StringBuilder();
        StringBuilder archiveCodes = new StringBuilder();
        for (YqdaborrowItem item : yqdaborrowItemList) {
            if (item.getArchiveData().get("TITLE") != null) {
                archiveNames.append(item.getArchiveData().get("TITLE")).append(";");
            }
            if (item.getArchiveData().get("XMMC") != null) {
                archiveNames.append(item.getArchiveData().get("XMMC")).append(";");
            }
            if (item.getArchiveData().get("DH") != null) {
                archiveCodes.append(item.getArchiveData().get("DH")).append(";");
            }
        }
        List<Map<String, Object>> data = remoteActivitiService.getProcessDateByProcessId(getInfo.getProcessId()).getData();
        StringBuilder assignees = new StringBuilder();
        for (Map<String, Object> item : data) {
            if (item.get("isAgree") == null || !String.valueOf(((LinkedHashMap) item.get("isAgree")).get("controlValue")).equals("同意")) {
                continue;
            }
            assignees.append(remoteUserService.getUserInfo
                            (String.valueOf(item.get("assignee")), SecurityUtils.getTenantCode(), SecurityConstants.INNER)
                    .getData().getSysUser().getNickName()).append("  ");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("menuId", 1);
        jsonObject.put("categoryId", 123456);
        jsonObject.put("type", "ty");
        StringBuilder dataBuilder = new StringBuilder();
        dataBuilder.append("{\"data\":[");
        dataBuilder.append("{\"borrowDate\":\"").append(borrowDate).append("\",");              //借阅日期
        dataBuilder.append("\"borrowDept\":\"").append(deptName).append("\",");                  //借阅部门
        dataBuilder.append("\"borrowUserName\":\"").append(username).append("\",");           //借阅人姓名
        dataBuilder.append("\"borrowUserPhone\":\"").append(getInfo.getPhoneNum()).append("\",");       //借阅人电话
        dataBuilder.append("\"borrowArchiveName\":\"").append(archiveNames.toString()).append("\","); //借阅档案名称
        dataBuilder.append("\"borrowArchiveCode\":\"").append(archiveCodes.toString()).append("\",");  //借阅档案档号
        dataBuilder.append("\"borrowUseTo\":\"").append(lymd).append("\",");                   //借阅用途
        dataBuilder.append("\"borrowApproveLeader\":\"").append(assignees).append("\"}");     //领导签字
        //dataBuilder.deleteCharAt(dataBuilder.length()-1);
        dataBuilder.append("]}");
        jsonObject.put("data", dataBuilder.toString());
        Map geturl = reportService.geturl(jsonObject);
        return success(geturl);
    }

    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PostMapping("/minusOne/{itemId}/{docId}")
    public AjaxResult borrowItemMinusOne(@PathVariable("itemId") String itemId,@PathVariable("docId") String docId) {
        YqdaborrowItem item = yqDaBorrowService.selectYqDaBorrowItemById(itemId);
        if ("0".equals(item.getDownloadable())) {
            return AjaxResult.warn("不允许下载");
        } else if (item.getDownloadCount() == 0) {
            return AjaxResult.warn("下载次数已耗尽");
        }
        //有次数，查询电子件下载次数
        YqdaBorrowItemPage yqdaBorrowItemPage = yqdaBorrowItemPageService.selectByItemIdAndDocId(itemId, docId);
        if (yqdaBorrowItemPage==null) {
            //没有电子件授权记录，新增第一次记录
            YqdaBorrowItemPage itemPage = new YqdaBorrowItemPage();
            itemPage.setId(String.valueOf(SnowflakeIdGenerator.generateId()));
            itemPage.setBorrowId(String.valueOf(item.getBorrowId()));
            itemPage.setItemId(itemId);
            itemPage.setDocId(docId);
            if (!"0".equals(item.getDownloadable())) {
                itemPage.setDownloadAllowCount(item.getDownloadCount()-1);
            }
            if (!"0".equals(item.getPrintable())) {
                itemPage.setPrintAllowCount(item.getPrintCount());
            }
            yqdaBorrowItemPageService.addYqdaBorrowItemPage(itemPage);
        }else {
            //下载记录有值
            if (yqdaBorrowItemPage.getDownloadAllowCount() == 0) {
                //该电子文件下载次数已耗尽，不允许下载
                return AjaxResult.warn("该电子文件下载次数已耗尽");
            }else {
                //允许下载，下载次数-1
                yqdaBorrowItemPage.setDownloadAllowCount(yqdaBorrowItemPage.getDownloadAllowCount()-1);
                yqdaBorrowItemPageService.updateYqdaBorrowItemPage(yqdaBorrowItemPage);
            }
        }
        //int i = yqDaBorrowService.borrowItemMinusOne(itemId);
        return AjaxResult.success("修改成功");
    }

    @Log(title = "archiveBorrow", businessType = BusinessType.UPDATE)
    @PostMapping("/minusOnePrint/{itemId}/{docId}")
    public AjaxResult borrowItemMinusOnePrint(@PathVariable("itemId") String itemId,@PathVariable("docId") String docId) {
        YqdaborrowItem item = yqDaBorrowService.selectYqDaBorrowItemById(itemId);
        if ("0".equals(item.getPrintable())) {
            return AjaxResult.warn("不允许打印");
        } else if (item.getPrintCount() == 0) {
            return AjaxResult.warn("打印次数已耗尽");
        }
        //有次数，查询电子件打印次数
        YqdaBorrowItemPage yqdaBorrowItemPage = yqdaBorrowItemPageService.selectByItemIdAndDocId(itemId, docId);
        if (yqdaBorrowItemPage==null) {
            //没有电子件授权记录，新增第一次记录
            YqdaBorrowItemPage itemPage = new YqdaBorrowItemPage();
            itemPage.setId(String.valueOf(SnowflakeIdGenerator.generateId()));
            itemPage.setBorrowId(String.valueOf(item.getBorrowId()));
            itemPage.setItemId(itemId);
            itemPage.setDocId(docId);
            if (!"0".equals(item.getDownloadable())) {
                itemPage.setDownloadAllowCount(item.getDownloadCount());
            }
            if (!"0".equals(item.getPrintable())) {
                itemPage.setPrintAllowCount(item.getPrintCount()-1);
            }
            yqdaBorrowItemPageService.addYqdaBorrowItemPage(itemPage);
        }else {
            //打印记录有值
            if (yqdaBorrowItemPage.getPrintAllowCount() == 0) {
                //该电子文件打印次数已耗尽，不允许打印
                return AjaxResult.warn("该电子文件打印次数已耗尽");
            }else {
                //允许打印，下载打印次数-1
                yqdaBorrowItemPage.setPrintAllowCount(yqdaBorrowItemPage.getPrintAllowCount()-1);
                yqdaBorrowItemPageService.updateYqdaBorrowItemPage(yqdaBorrowItemPage);
            }
        }
        //int i = yqDaBorrowService.borrowItemMinusOnePrint(itemId);
        return AjaxResult.success("修改成功");
    }

    @Log(title = "archiveBorrow", businessType = BusinessType.SELECT)
    @GetMapping("/selectPrint/{itemId}/{docId}")
    public AjaxResult borrowItemSelectPrint(@PathVariable("itemId") String itemId,@PathVariable("docId") String docId) {
        YqdaborrowItem item = yqDaBorrowService.selectYqDaBorrowItemById(itemId);
        if ("0".equals(item.getPrintable())) {
            return AjaxResult.success(0);
        } else if (item.getPrintCount() == 0) {
            return AjaxResult.success(0);
        }
        YqdaBorrowItemPage yqdaBorrowItemPage = yqdaBorrowItemPageService.selectByItemIdAndDocId(itemId, docId);
        if (yqdaBorrowItemPage==null) {
            //没有电子件授权记录，新增第一次记录
            YqdaBorrowItemPage itemPage = new YqdaBorrowItemPage();
            itemPage.setId(String.valueOf(SnowflakeIdGenerator.generateId()));
            itemPage.setBorrowId(String.valueOf(item.getBorrowId()));
            itemPage.setItemId(itemId);
            itemPage.setDocId(docId);
            if (!"0".equals(item.getDownloadable())) {
                itemPage.setDownloadAllowCount(item.getDownloadCount());
            }
            if (!"0".equals(item.getPrintable())) {
                itemPage.setPrintAllowCount(item.getPrintCount());
            }
            yqdaBorrowItemPageService.addYqdaBorrowItemPage(itemPage);
            return AjaxResult.success(itemPage.getPrintAllowCount());
        }else {
            //打印记录有值
            return AjaxResult.success(yqdaBorrowItemPage.getPrintAllowCount());
        }
        //return AjaxResult.success(item.getPrintCount());
    }

    /**
     * 通过categoryId和docId获取电子文件页数
     */
    @PostMapping("/getPageCount/{categoryId}/{docId}")
    public AjaxResult getPageCount(@PathVariable("categoryId") String categoryId, @PathVariable("docId") Long docId) throws Exception {
        TenantCategory category = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
        TenantYqdaDocument document = documentMapper.viewByDocid(docId, category.getEfileTableName(), new Yqdatransdoc().getTableName());
        String url = document.getDocMnt() + File.separator + document.getPath();
        logger.info(url);
        File file = new File(url);
        //判断文件类型，如果是有分页的文件，则返回页数
        FilePageCounter counter;
        if (file.exists()) {
            if (file.getName().endsWith(".pdf")) {
                counter = PdfFilePageCounter;
            } else if (url.endsWith(".ofd")) {
                counter = OfdFilePageCounter;
            } else if (file.getName().endsWith(".doc") || file.getName().endsWith(".docx")) {
                counter = WordFilePageCounter;
            } else if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) {
                counter = ExcelFilePageCounter;
            } else {
                logger.info("Unsupported file type.");
                return AjaxResult.warn("Unsupported file type.");
            }
            int pageCount = counter.getPageCount(file.getAbsolutePath());
            return AjaxResult.success(pageCount);
        } else {
            return AjaxResult.warn("文件不存在");
        }
    }

    /**
     * 通过YqdaBorrowItemPage的borrow_id和da_id、category_id判断YqdaBorrowItemPage表中是否已有数据，如果有则返回，没有则插入
     */
    @PostMapping("/getYqdaBorrowItemPage/{borrowId}/{daId}/{categoryId}/{docId}")
    public AjaxResult getYqdaBorrowItemPage(@PathVariable("borrowId") String borrowId, @PathVariable("daId") String daId, @PathVariable("categoryId") Long categoryId, @PathVariable("docId") String docId) {
        YqdaBorrowItemPage itemPage = new YqdaBorrowItemPage();
        itemPage.setBorrowId(borrowId);
        itemPage.setDaId(daId);
        itemPage.setCategoryId(categoryId);
        itemPage.setDocId(docId);
        itemPage.setTenantCode(SecurityUtils.getTenantCode());
        List<YqdaBorrowItemPage> yqdaBorrowItemPages = yqdaBorrowItemPageService.selectByEntity(itemPage);
        if (yqdaBorrowItemPages.size() == 0) {
            itemPage.setId(String.valueOf(SnowflakeIdGenerator.generateId()));
            itemPage.setCreateBy(SecurityUtils.getUsername());
            itemPage.setCreateTime(DateUtils.getNowDate());
            yqdaBorrowItemPageService.addYqdaBorrowItemPage(itemPage);
            return AjaxResult.success(itemPage);
        } else {
            return AjaxResult.success(yqdaBorrowItemPages.get(0));
        }
    }

    /**
     * 通过YqdaBorrowItemPage的id修改YqdaBorrowItemPage的page_allow_num字段
     */
    @GetMapping("/updateYqdaBorrowItemPage")
    public AjaxResult updateYqdaBorrowItemPage(@RequestParam("id") String id, @RequestParam("pageAllowNum") String pageAllowNum, @RequestParam("keyword") String keyword) {
        YqdaBorrowItemPage itemPage = new YqdaBorrowItemPage();
        itemPage.setId(id);
        itemPage.setPageAllowNum(pageAllowNum);
        itemPage.setUpdateBy(SecurityUtils.getUsername());
        itemPage.setUpdateTime(DateUtils.getNowDate());
        itemPage.setKeyword(keyword);
        return AjaxResult.success(yqdaBorrowItemPageService.updateYqdaBorrowItemPage(itemPage));
    }

    @Log(title = "预览", businessType = BusinessType.BROWSE)
    @PostMapping("/view")
    public void view(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String borrowId = String.valueOf(request.getParameter("borrowId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();
        String efiletable = "";
        if (null == daId || "null".equals(daId)) {
            //tenantCategory.setCategoryId(Long.parseLong(categoryId));
            TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
            efiletable = tenantCategory1.getEfileTableName();
        } else {
            efiletable = documentMapper.gettablenamebydaid(Long.parseLong(daId), allftable, catetablename);
        }
        TenantYqdaDocument document = documentMapper.viewByDocid(doc_id, efiletable, new Yqdatransdoc().getTableName());
        String url = document.getDocMnt() + File.separator + document.getPath();
        logger.info(url);
        if (url.equals("null")) {
            response.sendError(404, "File not found!");
            return;
        }
        response.reset(); // 非常重要
        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);
        if ("TXT".equals(document.getDocFileType())) {
            readTxtFile(url, document.getDocName(), response);
        } else {
            //在线预览，浏览器支持的文件类型都能打开
            URL u = new URL("file:///" + url);
            // 设置响应编码和类型
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + document.getDocName() + "\"");
            InputStream inputStream = null;
            //截取pdf第1，3，5-7页返回文件流
            FilePageCounter counter = null;
            YqdaBorrowItemPage yqdaBorrowItemPage = new YqdaBorrowItemPage();
            yqdaBorrowItemPage.setBorrowId(borrowId);
            yqdaBorrowItemPage.setDocId(String.valueOf(doc_id));
            yqdaBorrowItemPage.setTenantCode(SecurityUtils.getTenantCode());
            List<YqdaBorrowItemPage> yqdaBorrowItemPages = yqdaBorrowItemPageService.selectByEntity(yqdaBorrowItemPage);
            if (yqdaBorrowItemPages.size() != 0) {
                YqdaBorrowItemPage itemPage = yqdaBorrowItemPages.get(0);
                String pageAllowNum = itemPage.getPageAllowNum();
                if (pageAllowNum != null && !"".equals(pageAllowNum)) {
                    List<Integer> pageList = parsePageRange(pageAllowNum);
                    if (url.endsWith(".pdf")) {
                        counter = PdfFilePageCounter;
                    } else if (url.endsWith(".ofd")) {
                        counter = OfdFilePageCounter;
                    } else if (url.endsWith(".doc") || url.endsWith(".docx")) {
                        counter = WordFilePageCounter;
                    } else if (url.endsWith(".xls") || url.endsWith(".xlsx")) {
                        counter = ExcelFilePageCounter;
                    } else {
                        logger.info("Unsupported file type.");
                    }
                    inputStream = counter.extractPages(url, pageList);
                    if (inputStream == null) {
                        inputStream = new FileInputStream(url);
                    }
                } else {
                    inputStream = new FileInputStream(url);
                }

            } else {
                inputStream = new FileInputStream(url);
            }
            int len = 0;
            byte[] buf = new byte[4096];
            OutputStream out = response.getOutputStream();
            while ((len = inputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
                out.flush(); // 定期刷新输出流
            }
            System.gc();
            inputStream.close();
            out.close();
        }
    }

    public static List<Integer> parsePageRange(String pageAllowNum) {
        String[] pageNumStrings = pageAllowNum.split(",");
        List<Integer> pageList = new ArrayList<>();

        for (String pageNumString : pageNumStrings) {
            String[] rangeParts = pageNumString.split("-");
            if (rangeParts.length == 1) {
                // 单个数字
                pageList.add(Integer.parseInt(rangeParts[0]));
            } else if (rangeParts.length == 2) {
                // 范围表示（如5-7）
                int start = Integer.parseInt(rangeParts[0]);
                int end = Integer.parseInt(rangeParts[1]);

                if (start > end) {
                    throw new IllegalArgumentException("Invalid page range: " + pageNumString);
                }

                for (int i = start; i <= end; i++) {
                    pageList.add(i);
                }
            } else {
                throw new IllegalArgumentException("Invalid page number format: " + pageNumString);
            }
        }

        return pageList;
    }


    private void readTxtFile(String filePath, String fileName, HttpServletResponse response) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            UniversalDetector detector = new UniversalDetector(null);
            byte[] buf = new byte[4096];
            int nread;

            while ((nread = bis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }

            detector.dataEnd();
            //读取txt文件的编码格式
            String encoding = detector.getDetectedCharset();
            detector.reset();
            //以确定的编码格式读取文件
            OutputStream out = response.getOutputStream();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encoding))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    sb.append(System.lineSeparator());
                }
                String fileContent = sb.toString();
                // 之后你可以将fileContent作为你的响应内容
                response.setContentType("text/plain; charset=" + encoding); // 设置正确的编码格式
                response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
                out.write(fileContent.getBytes(encoding));
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Log(title = "获取遮挡关键词", businessType = BusinessType.OTHER)
    @PostMapping("/getKeyWord")
    public AjaxResult getKeyWord(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String borrowId = String.valueOf(request.getParameter("borrowId"));
        YqdaBorrowItemPage yqdaBorrowItemPage = new YqdaBorrowItemPage();
        yqdaBorrowItemPage.setBorrowId(borrowId);
        yqdaBorrowItemPage.setDocId(String.valueOf(doc_id));
        yqdaBorrowItemPage.setTenantCode(SecurityUtils.getTenantCode());
        String keyword = yqdaBorrowItemPageService.getKeyWord(yqdaBorrowItemPage);
        List<String> words = new ArrayList<>();
        if(keyword!=null && !"".equals(keyword.trim())) {
            words = Arrays.asList(keyword.split(","));
        }



        return AjaxResult.success(words);
    }


    @Log(title = "预览获取OFD文件路径", businessType = BusinessType.OTHER)
    @PostMapping("getOfdFile")
    public AjaxResult getOfdFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("viewOfd="+request.getParameter("docId"));
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        String borrowId = String.valueOf(request.getParameter("borrowId"));

        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();
        String efiletable = "";
        if (null == daId || "null".equals(daId)) {
            //tenantCategory.setCategoryId(Long.parseLong(categoryId));
            TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
            efiletable = tenantCategory1.getEfileTableName();
        } else {
            efiletable = documentMapper.gettablenamebydaid(Long.parseLong(daId), allftable, catetablename);
        }
        TenantYqdaDocument document = documentMapper.viewByDocid(doc_id, efiletable, new Yqdatransdoc().getTableName());
        String url = document.getDocMnt() + File.separator + document.getPath();
        File file = new File(url);
        if (!file.exists()) {
            return AjaxResult.error(404, "File not found!");
        } else {
            com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
            object.put("time", String.valueOf(new Date().getTime()));
            object.put("tenantCode", SecurityUtils.getTenantCode());
            //object.put("path", file.getAbsolutePath());
            object.put("docId", doc_id);
            object.put("daId",daId);
            object.put("categoryId",categoryId);
            object.put("borrowId",borrowId);
            object.put("userId", SecurityUtils.getUserId());
            String msg = object.toJSONString();
            logger.info(msg);
            msg = DESUtil.encrypt(msg);
            return AjaxResult.success(Base64Utils.encodeToUrlSafeString(msg.getBytes()));
        }
    }


    @GetMapping("viewOfd")
    public void viewOfd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String info = request.getParameter("token");
        if (StringUtils.isEmpty(info)) {
            throw new ServiceException("参数错误");
        } else {
            String msg = new String(Base64Utils.decodeFromUrlSafeString(info));
            String fileInfo = DESUtil.decrypt(msg);
            logger.info(fileInfo);
            JSONObject object = JSONObject.parseObject(fileInfo);



            Long doc_id = object.getLong("docId");
            String daId = object.getString("daId");
            String borrowId = object.getString("borrowId");
            String categoryId = object.getString("categoryId");

            String catetablename = object.getString("tenantCode").toUpperCase()+TenantCategory.BIGTABLENAME;
            String allftable = object.getString("tenantCode").toUpperCase()+TenantYqda.BIGTABLENAME;
            String efiletable = "";
            if (null == daId || "null".equals(daId)) {
                //tenantCategory.setCategoryId(Long.parseLong(categoryId));
                TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), catetablename);
                efiletable = tenantCategory1.getEfileTableName();
            } else {
                efiletable = documentMapper.gettablenamebydaid(Long.parseLong(daId), allftable, catetablename);
            }
            TenantYqdaDocument document = documentMapper.viewByDocid(doc_id, efiletable,object.getString("tenantCode").toUpperCase()+Yqdatransdoc.BIGTABLENAME);
            String url = document.getDocMnt() + File.separator + document.getPath();
            System.out.println(url);
            logger.info(url);
            if (url.equals("null")) {
                response.sendError(404, "File not found!");
                return;
            }
            response.reset(); // 非常重要
            // 设置 CORS 响应头
            ResponseUtils.defaultResponse(response);
            if ("TXT".equals(document.getDocFileType())) {
                readTxtFile(url, document.getDocName(), response);
            } else {
                //在线预览，浏览器支持的文件类型都能打开
                URL u = new URL("file:///" + url);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + document.getDocName() + "\"");
                InputStream inputStream = null;
                //截取pdf第1，3，5-7页返回文件流
                FilePageCounter counter = null;
                YqdaBorrowItemPage yqdaBorrowItemPage = new YqdaBorrowItemPage();
                yqdaBorrowItemPage.setBorrowId(borrowId);
                yqdaBorrowItemPage.setDocId(String.valueOf(doc_id));
                yqdaBorrowItemPage.setTenantCode(SecurityUtils.getTenantCode());
                List<YqdaBorrowItemPage> yqdaBorrowItemPages = yqdaBorrowItemPageService.selectByEntity(yqdaBorrowItemPage);
                if (yqdaBorrowItemPages.size() != 0) {
                    YqdaBorrowItemPage itemPage = yqdaBorrowItemPages.get(0);
                    String pageAllowNum = itemPage.getPageAllowNum();
                    if (pageAllowNum != null && !"".equals(pageAllowNum)) {
                        List<Integer> pageList = parsePageRange(pageAllowNum);
                        if (url.endsWith(".pdf")) {
                            counter = PdfFilePageCounter;
                        } else if (url.endsWith(".ofd")) {
                            counter = OfdFilePageCounter;
                        } else if (url.endsWith(".doc") || url.endsWith(".docx")) {
                            counter = WordFilePageCounter;
                        } else if (url.endsWith(".xls") || url.endsWith(".xlsx")) {
                            counter = ExcelFilePageCounter;
                        } else {
                            logger.info("Unsupported file type.");
                        }
                        inputStream = counter.extractPages(url, pageList);
                        if (inputStream == null) {
                            inputStream = new FileInputStream(url);
                        }
                    } else {
                        inputStream = new FileInputStream(url);
                    }

                } else {
                    inputStream = new FileInputStream(url);
                }
                int len = 0;
                byte[] buf = new byte[4096];
                OutputStream out = response.getOutputStream();
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                    out.flush(); // 定期刷新输出流
                }
                System.gc();
                inputStream.close();
                out.close();
            }
        }
    }
    @Log(title = "领取", businessType = BusinessType.OTHER)
    @PostMapping("/receive/{borrowId}")
    @PreAuthorize("@ss.hasPermi('archive:archiveBorrow:receive')")
    public AjaxResult receive(@PathVariable("borrowId") Long borrowId) throws Exception {
        String msg=yqDaBorrowService.receive(borrowId);
        return AjaxResult.success(msg);
    }
    @Log(title = "查看借阅单详情", businessType = BusinessType.SELECT)
    @PostMapping("/getdetail/{borrowId}")
    public AjaxResult getdetail(@PathVariable("borrowId") Long borrowId) throws Exception {
        return AjaxResult.success(yqDaBorrowService.getdetail(borrowId));
    }

}
